<template>
  <span class="animated-number" :title="value || '--'">{{ animatedValue || '--' }}</span>
</template>

<script setup>
import { ref, watch, onMounted } from '@vue/composition-api'

const props = defineProps({
  value: {
    type: [Number, String],
    default: '--'
  },
  duration: {
    type: Number,
    default: 1000
  }
})

const animatedValue = ref(0)

const animateNumber = (start, end) => {
  const startTime = performance.now()
  const updateValue = (currentTime) => {
    const elapsed = currentTime - startTime
    const progress = Math.min(elapsed / props.duration, 1)
    
    if (typeof start === 'number' && typeof end === 'number') {
      animatedValue.value = Math.floor(start + (end - start) * progress)
    } else {
      animatedValue.value = end
    }
    
    if (progress < 1) {
      requestAnimationFrame(updateValue)
    }
  }
  requestAnimationFrame(updateValue)
}

watch(() => props.value, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    animateNumber(oldVal, newVal)
  }
})

onMounted(() => {
  // 在组件挂载时，从0开始动画到目标值
  if (typeof props.value === 'number') {
    animateNumber(0, props.value)
  } else {
    animatedValue.value = props.value
  }
})
</script>

<style lang="scss" scoped>
.animated-number {
  display: inline-block;
}
</style> 